<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

function distributor_list_page()
{
    global $user;
    $user_info = _get_user_info($user->uid);
    if ($user_info['role'] === '经销商') {
        drupal_goto('distributor/edit/' . $user->uid, ['query' => ['distributor_id' => $user->uid]]);
    }
    @$output = drupal_render(drupal_get_form('distributor_list_form'));
    return $output;
}

function distributor_list_form($form, &$form_state)
{
    $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state);
    $form['address'] = _insert_address_selection_form($form, $form_state, 'address', 4, FALSE, '', '', '', TRUE);
    $form['distributor_fuzzy_search']['#markup'] = '<div class="distributor-fuzzy-search">';
    $form['status'] =  _insert_user_upgrade_status_selection_form($form, $form_state,$role="distributor",$init_value = "");
    $form['fuzzy_address'] = array(

        '#type' => 'textfield',
        '#default_value' => !empty($form_state['values']['fuzzy_address']) ? $form_state['values']['fuzzy_address'] : '',
        '#attributes' => array('placeholder' => '详细地址'),
        '#validated' => TRUE,
    );
    $form['distributor'] = array(
        '#attributes' => array('placeholder' => '经销商名称'),
        '#type' => 'textfield',
        '#default_value' => !empty($form_state['values']['plant']) ? $form_state['values']['plant'] : '',
        '#id'=>'distributor_option',
    );
    if(user_access('add distributor')) {
        $form['distributor_manage'] = array(
                '#markup' => '<a  href="' . base_path() . 'distributor/add"  class="btn btn-primary" target="_blank" style="float:left;margin-left:10px">添加经销商</a>',
            );

    }
    $form['distributor_fuzzy_search_close']['#markup'] = '</div>';
    $table['#markup'] = data_list_view_page($form, $form_state);
    ajax_submit_form($form, $form_state, $table, '');
    return $form;
}


function distributor_list_form_validate($form, &$form_state)
{
}

function data_list_view_page($form = '', &$form_state = '')
{
    global $user;
    $output = '';
    //表头
    $header = array(
        array('data' => '选择', 'class' => ['essential no']),
        array('data' => '地址', 'class' => ['essential province city county']),
        array('data' => '经销商名称', 'class' => ['essential distributor']),
        array('data' => '关内/关外', 'class' => ['integrant essential inorout'], 'field' => 'inorout'),
        array('data' => '电话', 'class' => ['essential break phone']),
        array('data' => '手机号码', 'class' => ['essential cell']),
        array('data' => '邮箱', 'class' => ['essential break email']),
        array('data' => '状态', 'class' => ['integrant essential break status'], 'field' => 'status'),
        array('data' => '操作', 'class' => ['essential more']),
    );
    $query = db_select('addr', 'A')->extend('PagerDefault')->extend('TableSort');//地址表
    $query->join('distributor', 'D', 'A.addr_id=D.addr_id');//内连接 成一个表
    $query->fields('D');

    //地址级别查询
    _address_search_conditon($query,$form_state);
    //模糊条件筛选
    if (!empty($form_state['values']['fuzzy_address'])) {//模糊地址查询条件
        $query->condition('D.addr_details', '%' . db_like($form_state['values']['fuzzy_address']) . '%', 'LIKE');
    }
    if (!empty($form_state['values']['distributor'])) {//模糊植物名字查询条件
        $query->condition('D.distributor_name', '%' . db_like($form_state['values']['distributor']) . '%', 'LIKE');
    }
    if (!empty($form_state['values']['status'])) {//模糊植物名字查询条件
        $query->condition('D.status',$form_state['values']['status']);
    }

    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    if (empty($form_state['values']) || empty($form_state['values']['order'])) {
        $query->orderBy('D.timestamp', 'DESC');
    }
    $query->limit(variable_get("list_page_item_number", 5));
    $distributorInfo = $query->orderByHeader($header)->execute();

    $rows = array();
    //表内容
    $n = 1;
    foreach ($distributorInfo as $row) {
        $city = $row->city ? ' ' . $row->city : '';
        $county = $row->county ? ' ' . $row->county : '';
        if (nonghua_user_access('distributor', 'delete', $row->distributor_id, $row->author_uid, $row->distributor_id)) {
            $disabled = ' class="listViewTableCheck" ';
        } else {
            $disabled = ' disabled="true" ';
        }
        $rows[] = array(
            array('data' => '<input type="checkbox"' . $disabled . ' value ="' . $row->distributor_id . '"/>' . $n++, 'class' => ['integrant essential no']),
            array('data' => $row->province . $city . $county, 'class' => ['integrant essential province city county']),
            array('data' => '<a href="' . base_path() . 'distributor/edit/' . $row->distributor_id . '?distributor_id=' . $row->distributor_id . '" data-toggle="modal" target = "_top">' . $row->distributor_name . '</a>', 'class' => ['integrant haveTobr essential distributor']),
            array('data' => $row->inorout, 'class' => ['integrant goRight essential inorout']),
            array('data' => $row->phone, 'class' => ['essential break phone']),
            array('data' => $row->cell, 'class' => ['essential cell']),
            array('data' => $row->email, 'class' => ['essential break email']),
            array('data' => $row->status, 'class' => ['integrant haveTobr essential break status']),
            array('data' => '<a href="' . base_path() . 'distributor/edit/' . $row->distributor_id . '" data-toggle="modal" target = "_top"><img width="20px" height="20px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more'),
        );
    }

    $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('没有记录'), 'attributes' => array('class' => array('table table-bordered table-striped table-hover enhanced')))); //表格
    /*	 * *按钮** */
    if (sizeof($rows) > 0 && (user_access('delete own distributor') || user_access('delete all distributor'))) {
        $output .= '<a href="javascript:void(0)" id="listViewTableSelectAll" data-toggle="modal" class="btn btn-mini">全选</a>';
        $output .= '<a href="javascript:void(0)" id="listViewTableDeleteSelected" data-toggle="modal" class="btn btn-mini">删除所选</a>';
    }
    if(!empty($form_state['values']['village'])){
        $addr_id = $form_state['values']['village'];
        $str = 'village=';
    }elseif(!empty($form_state['values']['town'])){
        $addr_id = $form_state['values']['town'];
        $str = 'town=';
    }elseif(!empty($form_state['values']['county'])){
        $addr_id = $form_state['values']['county'];
        $str = 'county=';
    }elseif(!empty($form_state['values']['city'])){
        $addr_id = $form_state['values']['city'];
        $str = 'city=';
    }elseif(!empty($form_state['values']['province'])){
        $addr_id = $form_state['values']['province'];
        $str = 'province=';
    }
    $str .= $addr_id;
    $output .= '<a href="'.base_path().'distributor/export?'.$str.'&address_fuzzy='.$form_state['values']['address_fuzzy'].'&status='.$form_state['values']['status'].'&distributor='.$form_state['values']['distributor'].'&fuzzy_address='.$form_state['values']['fuzzy_address'].'" data-toggle="modal" class="btn btn-mini">导出</a>';

    $output .= theme('pager');
    return $output;
}

function distributor_delete()
{
    ajax_table_delete('distributor', 'distributor_id', true);
}

function distributor_export($form,&$form_state){
    $letter = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
    $tableheader = array('地址','经销商','关内/关外','电话','手机','邮箱','状态','详细地址');
    $data = get_distributor_data($form, $form_state);
    nonghua_php_excel($letter,$tableheader,$data,'经销商信息数据');
}

function get_distributor_data($form = '', &$form_state = ''){
    global $user;
    $user_info = _get_user_info($user->uid);
    $query = db_select('addr', 'A');//地址表
    $query->join('distributor', 'D', 'A.addr_id=D.addr_id');//内连接 成一个表
    

    //地址级别查询
    if (!empty($_GET['town'])) {//乡镇级
        $query->condition('A.town_id', $_GET['town'], '=');
    } elseif (!empty($_GET['county'])) {//县级
        $query->condition('A.county_id', $_GET['county'], '=');
    } elseif (!empty($_GET['city'])) {//市级
        $query->condition('A.city_id', $_GET['city'], '=');
    } elseif (!empty($_GET['province'])) {//省级
        $query->condition('A.province_id', $_GET['province'], '=');
    }
    if (!user_access('view all distributor') && user_access('view own distributor')) {
        $query->condition('D.author_uid', $user->uid, '=');
    }
    if (!empty($form_state['values']['address_fuzzy'])) {
        if (!empty($form_state['values']['city'])) {//县级
            $or = db_or()->condition('A3.name', '%' . db_like($_GET['address_fuzzy']) . '%', 'like')->condition('A2.name', '%' . db_like($_GET['address_fuzzy']) . '%', 'like');
        } elseif (!empty($_GET['province'])) {//省级
            $or = db_or()->condition('A3.name', '%' . db_like($_GET['address_fuzzy']) . '%', 'like')->condition('A2.name', '%' . db_like($_GET['address_fuzzy']) . '%', 'like')->condition('A1.name', '%' . db_like($_GET['address_fuzzy']) . '%', 'like');
        } else {
            $or = db_or()->condition('A3.name', '%' . db_like($_GET['address_fuzzy']) . '%', 'like')->condition('A2.name', '%' . db_like($_GET['address_fuzzy']) . '%', 'like')->condition('A1.name', '%' . db_like($_GET['address_fuzzy']) . '%', 'like')->condition('A.name', '%' . db_like($_GET['address_fuzzy']) . '%', 'like');
        }
        $query->condition($or);
    }
    //模糊条件筛选
    if (!empty($_GET['fuzzy_address'])) {//模糊地址查询条件
        $query->condition('D.addr_details', '%' . db_like($_GET['fuzzy_address']) . '%', 'LIKE');
    }
    if (!empty($_GET['distributor'])) {//模糊植物名字查询条件
        $query->condition('D.distributor_name', '%' . db_like($_GET['distributor']) . '%', 'LIKE');
    }
    if (!empty($_GET['status'])) {//模糊植物名字查询条件
        $query->condition('D.status',$_GET['status']);
    }

    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    $query->fields('D',array('distributor_name','inorout','phone','cell','email','status','addr_details'));
    if (empty($form_state['values']) || empty($form_state['values']['order'])) {
        $query->orderBy('D.timestamp', 'DESC');
    }


    $distributorInfo = $query->execute()->fetchAll();
    foreach($distributorInfo as $k => $v){
        $distributorInfo[$k]->province= $v->province.$v->city.$v->county.$v->town.$v->village;
        unset($distributorInfo[$k]->city);
        unset($distributorInfo[$k]->county);
        unset($distributorInfo[$k]->town);
        unset($distributorInfo[$k]->village);
    }
    return $distributorInfo;
}